package main

import (
	"encoding/json"
	"io/ioutil"
	"time"

	"github.com/labstack/echo/v4"
)

type VoyageUpdatePayload struct {
	Timestamp time.Time
	Longitude float64
	Latitude  float64
	SpeedKmph float64
	TrueTrack float64
}

func voyageUpdator(c echo.Context) error {
	shipIDStr := c.Param("ship_id")
	shipID, err := ParseShipID(shipIDStr)
	if err != nil {
		return err
	}
	body := c.Request().Body
	content, err := ioutil.ReadAll(body)
	if err != nil {
		return err
	}
	var data VoyageUpdatePayload
	err = json.Unmarshal(content, &data)
	if err != nil {
		return err
	}
	context := FromEchoContext(c)
	repo, err := context.GetShipVoyageRepo()
	if err != nil {
		return err
	}
	voyage, err := repo.GetByShipID(shipID)
	if err != nil {
		return err
	}
	newState, err := voyage.Update(context, data)
	if err != nil {
		return err
	}
	err = repo.Update(newState)
	return err
}
